<script setup>
import { ref, onMounted, reactive, computed, nextTick, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../stores/user'
import axios from 'axios'

const userStore = useUserStore()
const isHR = computed(() => userStore.isHR)

const loading = ref(false)
const employees = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogTitle = ref('添加员工')
const isEdit = ref(false)
const employeeTable = ref(null)
const tableHeight = ref('calc(100vh - 140px)')
const searchQuery = ref('')

const formRef = ref(null)
const positions = ref([])
const form = reactive({
  id: null,
  username: '',
  name: '',
  password: '123456',
  phone: '',
  email: '',
  departmentId: '',
  positionId: '',
  role: 'EMPLOYEE',
  status: 'ACTIVE',
  leaveReason: ''
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  departmentId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  positionId: [{ required: true, message: '请选择职位', trigger: 'change' }],
  leaveReason: [
    { 
      required: true, 
      message: '请输入离职原因', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (form.status === 'LEFT' && (!value || value.trim() === '')) {
          callback(new Error('离职时必须填写离职原因'))
        } else {
          callback()
        }
      }
    }
  ]
}

const departments = ref([])

// 获取部门列表
const fetchDepartments = async () => {
  try {
    const response = await axios.get('/departments')
    departments.value = response.data
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败，请重试')
  }
}

// 获取岗位列表
const fetchPositions = async () => {
  try {
    const response = await axios.get('/positions')
    positions.value = response.data
  } catch (error) {
    ElMessage.error('获取岗位列表失败，请重试')
  }
}

// 获取员工分页列表
const fetchEmployees = async () => {
  try {
    loading.value = true
    const response = await axios.get('/users/page', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        keyword: searchQuery.value || undefined
      }
    })
    const data = response.data || {}
    employees.value = Array.isArray(data.records) ? data.records : []
    total.value = typeof data.total === 'number' ? data.total : 0
    loading.value = false
  } catch (error) {
    console.error('获取员工列表失败:', error)
    ElMessage.error('获取员工列表失败，请重试')
    loading.value = false
  }
}

// 打开添加员工对话框
const openAddDialog = () => {
  isEdit.value = false
  dialogTitle.value = '添加员工'
  form.id = null
  form.username = ''
  form.name = ''
  form.password = '123456'
  form.phone = ''
  form.email = ''
  form.departmentId = ''
  form.positionId = ''
  form.role = 'EMPLOYEE'
  form.status = 'ACTIVE'
  form.leaveReason = ''
  dialogVisible.value = true
}

// 打开编辑员工对话框
const openEditDialog = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑员工'
  form.id = row.id
  form.username = row.username
  form.name = row.name || row.username
  form.password = ''
  form.phone = row.phone
  form.email = row.email
  form.departmentId = row.departmentId
  form.positionId = row.positionId
  form.role = row.role || 'EMPLOYEE'
  form.status = row.status || 'ACTIVE'
  form.leaveReason = row.leaveReason || ''
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        if (isEdit.value) {
          // 编辑员工 - 构建更新请求数据
          const updateData = {
            name: form.name,
            email: form.email,
            phone: form.phone,
            role: form.role,
            departmentId: form.departmentId,
            positionId: form.positionId,
            status: form.status,
            leaveReason: form.status === 'LEFT' ? form.leaveReason : null
          }
          
          // 如果密码不为空，则更新密码
          if (form.password && form.password.trim() !== '') {
            updateData.password = form.password
          }
          
          const response = await axios.put(`/users/${form.id}`, updateData)
          ElMessage.success('员工信息更新成功')
        } else {
          // 添加员工
          const response = await axios.post('/auth/register', form)
          ElMessage.success('员工添加成功')
        }
        
        // 重新获取员工列表
        fetchEmployees()
        dialogVisible.value = false
      } catch (error) {
        console.error('提交员工信息失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        loading.value = false
      }
    }
  })
}

// 快速离职
const handleLeave = (row) => {
  ElMessageBox.prompt('请输入离职原因', '员工离职', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入离职原因',
    inputPattern: /\S+/,
    inputErrorMessage: '离职原因不能为空'
  }).then(async ({ value }) => {
    try {
      loading.value = true
      const updateData = {
        status: 'LEFT',
        leaveReason: value
      }
      await axios.put(`/users/${row.id}`, updateData)
      ElMessage.success('员工离职操作成功')
      fetchEmployees()
    } catch (error) {
      console.error('离职操作失败:', error)
      ElMessage.error('离职操作失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除员工 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      loading.value = true
      await axios.delete(`/users/${row.id}`)
      ElMessage.success('员工删除成功')
      // 重新获取员工列表
      fetchEmployees()
    } catch (error) {
      console.error('删除员工失败:', error)
      ElMessage.error('删除失败，请重试')
    } finally {
      loading.value = false
    }
  }).catch(() => {})
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return String(dateTime)
    }
    // yyyy/M/d HH:mm:ss
    const y = date.getFullYear()
    const m = date.getMonth() + 1
    const d = date.getDate()
    const hh = String(date.getHours()).padStart(2, '0')
    const mm = String(date.getMinutes()).padStart(2, '0')
    const ss = String(date.getSeconds()).padStart(2, '0')
    return `${y}/${m}/${d} ${hh}:${mm}:${ss}`
  } catch (error) {
    return String(dateTime)
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  try {
    const dateObj = new Date(date)
    if (isNaN(dateObj.getTime())) {
      return String(date)
    }
    // yyyy/M/d
    const y = dateObj.getFullYear()
    const m = dateObj.getMonth() + 1
    const d = dateObj.getDate()
    return `${y}/${m}/${d}`
  } catch (error) {
    return String(date)
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  // 如果status为null或undefined，默认为在职
  if (!status || status === 'ACTIVE' || status === null) {
    return 'success'
  }
  return 'danger'
}

// 获取状态显示文本
const getStatusText = (status) => {
  // 如果status为null或undefined，默认为在职
  if (!status || status === 'ACTIVE' || status === null) {
    return '在职'
  }
  return '离职'
}

// 计算表格高度，实现自适应
const calcTableHeight = () => {
  nextTick(() => {
    const windowHeight = window.innerHeight
    const headerHeight = document.querySelector('.page-header')?.offsetHeight || 60
    const padding = 40 // 上下内边距
    tableHeight.value = `${windowHeight - headerHeight - padding}px`
  })
}

// 处理表头拖动事件
const handleHeaderDragend = () => {
  nextTick(() => {
    if (employeeTable.value) {
      employeeTable.value.doLayout()
    }
  })
}

// 监听窗口大小变化
const handleResize = () => {
  calcTableHeight()
}

// 分页变化
const handlePageChange = (newPage) => {
  pageNum.value = newPage
  fetchEmployees()
}
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  pageNum.value = 1
  fetchEmployees()
}

// 监听状态变化
watch(() => form.status, (newStatus) => {
  if (newStatus === 'ACTIVE') {
    form.leaveReason = ''
  }
})

// 搜索时重置页码并请求
watch(searchQuery, () => {
  pageNum.value = 1
  fetchEmployees()
})

onMounted(() => {
  fetchDepartments()
  fetchPositions()
  fetchEmployees()
  calcTableHeight()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<template>
  <div class="employee-container">
    <div class="page-header">
      <div class="page-title">员工管理</div>
      <div class="header-actions">
        <!-- 添加搜索框 -->
        <el-input
          v-model="searchQuery"
          placeholder="搜索员工姓名、用户名、邮箱、电话、部门或职位"
          clearable
          prefix-icon="el-icon-search"
          style="width: 350px; margin-right: 15px;"
        />
        <el-button 
          type="primary" 
          @click="openAddDialog" 
          v-if="isHR"
        >
          <el-icon><Plus /></el-icon>添加员工
        </el-button>
      </div>
    </div>
    
    <div class="table-container">
      <el-table 
        ref="employeeTable"
        :data="employees" 
        border 
        style="width: 100%" 
        v-loading="loading"
        :height="tableHeight"
        @header-dragend="handleHeaderDragend"
      >
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="departmentName" label="部门" width="100" />
        <el-table-column prop="positionName" label="职位" width="120" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="row.role === 'HR_ADMIN' ? 'danger' : row.role === 'DEPARTMENT_MANAGER' ? 'warning' : 'success'">
              {{ row.role === 'HR_ADMIN' ? '人事管理员' : row.role === 'DEPARTMENT_MANAGER' ? '部门管理员' : '普通员工' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="entryDate" label="入职时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.entryDate) || formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="leaveDate" label="离职时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.leaveDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" v-if="isHR">
          <template #default="{ row }">
            <div style="display: flex; gap: 5px; align-items: center;">
              <el-button 
                type="primary" 
                size="small" 
                @click="openEditDialog(row)"
              >
                编辑
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="handleLeave(row)"
                v-if="row.status === 'ACTIVE'"
              >
                离职
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin: 20px 0; text-align: right;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 20, 50, 100]"
      />
    </div>
    
    <!-- 添加/编辑员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" v-if="isEdit">
          <el-input v-model="form.password" placeholder="不修改密码请留空" type="password" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择部门" style="width: 100%">
            <el-option
              v-for="item in departments"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="职位" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择职位" style="width: 100%">
            <el-option
              v-for="item in positions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
            <el-option label="普通员工" value="EMPLOYEE" />
            <el-option label="部门管理人员" value="DEPARTMENT_MANAGER" />
            <el-option label="企业人事" value="HR_ADMIN" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="员工状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="在职" value="ACTIVE" />
            <el-option label="离职" value="LEFT" />
          </el-select>
        </el-form-item>
        
        <el-form-item 
          label="离职原因" 
          prop="leaveReason" 
          v-if="form.status === 'LEFT'"
        >
          <el-input 
            v-model="form.leaveReason" 
            type="textarea" 
            :rows="3"
            placeholder="请输入离职原因" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
}

.employee-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.table-container {
  flex: 1;
  padding: 0 20px 20px;
  background-color: #fff;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

/* 确保表格占满整个空间 */
:deep(.el-table) {
  flex: 1;
  overflow: hidden;
}

/* 调整表格行高 */
:deep(.el-table__row) {
  height: 50px;
}

/* 调整表格头部样式 */
:deep(.el-table__header) {
  font-weight: bold;
  background-color: #f5f7fa;
}

/* 表格行悬停效果 */
:deep(.el-table__row:hover) {
  background-color: #f0f8ff !important;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  :deep(.el-table .cell) {
    white-space: nowrap;
  }
}
</style> 